import websocket
import redis
import json
import requests
import numpy as np
from datetime import datetime

pool = redis.ConnectionPool(host='localhost',
                            port=6379,
                            decode_responses=True,
                            db=0)
r = redis.Redis(connection_pool=pool)


class ws_orderbook:

    def __init__(self, symbol, interval):
        self.symbol = symbol
        self.interval = interval
        self.count = 0

    def get_rest_snapshot(self):
        url = f'https://api.binance.com/api/v3/depth?symbol={self.symbol.upper()}&limit=1000'
        res = requests.get(url)
        data = json.loads(res.text.encode())
        snapshot_updateId = data['lastUpdateId']
        return snapshot_updateId

    def on_message(self, ws, message):
        r.lpush(f'{self.symbol}_orderbook', message)
        self.count += 1

        if self.count > 1000:
            r.ltrim(f'{self.symbol}_orderbook', 0, 100)

    def on_error(self, ws, error):
        print(error)

    def on_close(self, close_msg):
        print("### closed ###" + close_msg)

    def streamKline(self):
        websocket.enableTrace(False)
        socket = f'wss://stream.binance.com:9443/ws/{self.symbol}@depth@{self.interval}'
        ws = websocket.WebSocketApp(socket,
                                    on_message=self.on_message,
                                    on_error=self.on_error,
                                    on_close=self.on_close)

        ws.run_forever()


ob = ws_orderbook('solusdt', '1000ms')
ob.streamKline()